package com.wxp.demo05.text;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.wxp.demo05.R;
import com.wxp.demo05.util.LogUtils;
import com.wxp.demo05.util.ViewUtil;

/**
 * 3.4 编辑框自动隐藏输入法
 */
public class EditHideActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_edit_hide);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        this.setTitle("3.4 编辑框自动隐藏输入法");

        //注册文件变化监听器
        EditText et_phone = this.findViewById(R.id.et_phone);
        EditText et_password = this.findViewById(R.id.et_password);

        et_phone.addTextChangedListener(new HideTextWatcher(et_phone, this.getResources().getInteger(R.integer.phone_max_length)));
        et_password.addTextChangedListener(new HideTextWatcher(et_password, this.getResources().getInteger(R.integer.password_max_length)));
    }

    /**
     * 隐藏文本监听类
     */
    private class HideTextWatcher implements TextWatcher {
        /**
         * 定义编辑框
         */
        private EditText myEditText;
        /**
         * 定义最大长度
         */
        private Integer myMaxLength;

        public HideTextWatcher(EditText editText, int maxLength) {
            this.myEditText = editText;
            this.myMaxLength = maxLength;
        }


        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            LogUtils.info("文件改变前事件--》");
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            LogUtils.info("文件改变事件--》");
        }

        @Override
        public void afterTextChanged(Editable s) {
            LogUtils.info("文件改变后事件--》");
            //获取已输入的文本
            String inputText = s.toString();
            //判断长度是否满足
            if (inputText.length() == myMaxLength) {
                //隐藏输入法键盘
                ViewUtil.hideOneInputMethod(EditHideActivity.this, myEditText);
            }
        }
    }
}